#include "DlgProc.h"
#include "resource.h"
#include "FileDialogs.h"
#include <stdio.h>

BOOL CALLBACK DlgProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static HWND previewWnd;

	switch (msg)
	{
	case WM_INITDIALOG:
		{
			if (!(previewWnd = FindWindowEx(wnd, NULL, TEXT("FontPreview"), NULL)))
			{
				goto Exit;
			}
			return TRUE;
		}
	case WM_CLOSE:
		{
Exit:
			EndDialog(wnd, 0);
			PostQuitMessage(0);
			return TRUE;
		}
	case WM_COMMAND:
		{
			int notifyCode = HIWORD(wParam);
			int id = LOWORD(wParam);
			HWND wndCtl = (HWND)lParam;

			switch (id)
			{
			case IDC_FONTLIST:
				{
					if (notifyCode != LBN_SELCHANGE)
						break;
					
					SendDlgItemMessage(wnd, IDC_FONTPREVIEW, WM_USER, 0, 0);
					return FALSE;
				}
			case IDC_FONTSIZELIST:
				{
					if (notifyCode != LBN_SELCHANGE)
						break;
					
					SendDlgItemMessage(wnd, IDC_FONTPREVIEW, WM_USER, 0, 0);
					return FALSE;
				}
			case IDC_CHKBOLD:
				{
					if (notifyCode != BN_CLICKED)
						break;

					SendDlgItemMessage(wnd, IDC_FONTPREVIEW, WM_USER, 0, 0);
					return FALSE;
				}
			case IDC_CHKITALIC:
				{
					if (notifyCode != BN_CLICKED)
						break;
					
					SendDlgItemMessage(wnd, IDC_FONTPREVIEW, WM_USER, 0, 0);
					return FALSE;
				}
			case IDC_BTNSAVE:
				{
					static const TCHAR* gbaExtWithDot = TEXT(".gbafont");
					static const TCHAR* saveFileDlgFilter [] = {TEXT("gbafont"), NULL};
					TCHAR filePath[512];
					FILE* gbaFontFile;

					if (!SaveFileDlg(filePath, TEXT("GBA Font"), saveFileDlgFilter, wnd))
						return FALSE;

					if (!wcsstr(filePath, saveFileDlgFilter[0]))
						wcscat(filePath, gbaExtWithDot);

					gbaFontFile = _wfopen(filePath, L"w");
					
					SendDlgItemMessage(wnd, IDC_FONTPREVIEW, WM_USER + 1, (WPARAM)gbaFontFile, 0);

					fclose(gbaFontFile);
					return FALSE;
				}
			}
		}
	}
	return FALSE;
}